package net.chat;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Class representing a message.
 * @author Prabhat
 */
public class Message {
    // attributes

    private static int lastMid = 0;
    private int mid;
    private String message;
    private Date sent;
    private User fromUser;
    private List<User> deliveredUsers; // list of users to which message has been delivered

    // constructor
    public Message(String message, User fromUser) {
        this.mid = lastMid + 1;
        lastMid = this.mid;
        this.message = message;
        this.sent = new Date();
        this.fromUser = fromUser;
        this.deliveredUsers = new ArrayList<User>();
    }

    // getters
    public int getMid() {
        return mid;
    }

    public String getMessage() {
        return message;
    }

    public Date getSent() {
        return sent;
    }

    public User getFromUser() {
        return fromUser;
    }

    public List<User> getDeliveredUsers() {
        return deliveredUsers;
    }

    // add user to the delivered list so message is not sent twice.
    public boolean deliver(User user) {
        synchronized (deliveredUsers) {
            boolean delivered = false;

            if (!deliveredUsers.contains(user)) {
                deliveredUsers.add(user);
                delivered = true;
            }
            return delivered;
        }
    }
}
